package cn.harry.cabinet.view.fragments

import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.lifecycle.lifecycleScope
import cn.harry.cabinet.R
import cn.harry.cabinet.model.entity.Configuration
import cn.harry.cabinet.repository.ConfigurationRepository
import cn.harry.cabinet.utils.AppConfigKeys
import cn.harry.cabinet.utils.logConfigChange
import com.arcsoft.face.ActiveFileInfo
import com.arcsoft.face.ErrorInfo
import com.arcsoft.face.FaceEngine
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.Date

/**
 * 人脸识别配置Fragment
 * 用于配置虹软人脸识别引擎的APP_ID和SDK_KEY
 */
class FaceRecognitionFragment : BaseFragment() {
    
    companion object {
        private const val TAG = "FaceRecognitionFragment"
    }
    
    private lateinit var etAppId: EditText
    private lateinit var etSdkKey: EditText
    private lateinit var tvActivationStatus: TextView
    private lateinit var btnActivateEngine: Button
    private lateinit var btnSaveConfig: Button
    
    private lateinit var repository: ConfigurationRepository
    
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_face_recognition_config, container, false)
    }
    
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        
        repository = ConfigurationRepository(requireActivity().application)
        
        initViews(view)
        setupListeners()
        loadConfigs()
        checkActivationStatus()
        
        // 防止页面打开时自动弹出键盘
        hideKeyboardOnLoad()
    }
    
    /**
     * 初始化视图
     */
    private fun initViews(view: View) {
        etAppId = view.findViewById(R.id.et_app_id)
        etSdkKey = view.findViewById(R.id.et_sdk_key)
        tvActivationStatus = view.findViewById(R.id.tv_activation_status)
        btnActivateEngine = view.findViewById(R.id.btn_activate_engine)
        btnSaveConfig = view.findViewById(R.id.btn_save_config)
    }
    
    /**
     * 设置监听器
     */
    private fun setupListeners() {
        btnSaveConfig.setOnClickListener {
            saveConfigs()
        }
        
        btnActivateEngine.setOnClickListener {
            activateEngine()
        }
    }
    
    /**
     * 加载配置
     */
    private fun loadConfigs() {
        viewLifecycleOwner.lifecycleScope.launch {
            try {
                val configs = withContext(Dispatchers.IO) {
                    repository.getByType(AppConfigKeys.TYPE_FACE_RECOGNITION)
                }
                
                val configMap = configs.associateBy { it.key }
                
                etAppId.setText(configMap[AppConfigKeys.KEY_FACE_APP_ID]?.value ?: "")
                etSdkKey.setText(configMap[AppConfigKeys.KEY_FACE_SDK_KEY]?.value ?: "")
                
            } catch (e: Exception) {
                Log.e(TAG, "加载配置失败", e)
                Toast.makeText(requireContext(), "加载配置失败: ${e.message}", Toast.LENGTH_SHORT).show()
            }
        }
    }
    
    /**
     * 保存配置
     */
    private fun saveConfigs() {
        val appId = etAppId.text.toString().trim()
        val sdkKey = etSdkKey.text.toString().trim()
        
        if (appId.isEmpty()) {
            Toast.makeText(requireContext(), "请输入APP_ID", Toast.LENGTH_SHORT).show()
            return
        }
        
        if (sdkKey.isEmpty()) {
            Toast.makeText(requireContext(), "请输入SDK_KEY", Toast.LENGTH_SHORT).show()
            return
        }
        
        viewLifecycleOwner.lifecycleScope.launch {
            try {
                // 获取旧值
                val oldValues = withContext(Dispatchers.IO) {
                    val oldAppId = repository.getByTypeAndKey(
                        AppConfigKeys.TYPE_FACE_RECOGNITION,
                        AppConfigKeys.KEY_FACE_APP_ID
                    )?.value ?: ""
                    val oldSdkKey = repository.getByTypeAndKey(
                        AppConfigKeys.TYPE_FACE_RECOGNITION,
                        AppConfigKeys.KEY_FACE_SDK_KEY
                    )?.value ?: ""
                    Pair(oldAppId, oldSdkKey)
                }
                
                withContext(Dispatchers.IO) {
                    upsertConfig(AppConfigKeys.KEY_FACE_APP_ID, appId)
                    upsertConfig(AppConfigKeys.KEY_FACE_SDK_KEY, sdkKey)
                }
                
                // 构建变更详情
                val changes = mutableListOf<String>()
                if (oldValues.first != appId) {
                    val oldMask = if (oldValues.first.isNotEmpty()) "****${oldValues.first.takeLast(4)}" else "(空)"
                    val newMask = "****${appId.takeLast(4)}"
                    changes.add("APP_ID: $oldMask → $newMask")
                }
                if (oldValues.second != sdkKey) {
                    val oldMask = if (oldValues.second.isNotEmpty()) "****${oldValues.second.takeLast(4)}" else "(空)"
                    val newMask = "****${sdkKey.takeLast(4)}"
                    changes.add("SDK_KEY: $oldMask → $newMask")
                }
                
                // 记录日志
                if (changes.isNotEmpty()) {
                    requireContext().logConfigChange(
                        scope = viewLifecycleOwner.lifecycleScope,
                        subType = "FACE_ENGINE_CONFIG",
                        description = "修改人脸识别引擎配置: ${changes.joinToString(", ")}",
                        oldValue = "APP_ID: ${if (oldValues.first.isNotEmpty()) "****" else "(空)"}, SDK_KEY: ${if (oldValues.second.isNotEmpty()) "****" else "(空)"}",
                        newValue = changes.joinToString("\n")
                    )
                }
                
                Toast.makeText(requireContext(), "保存成功", Toast.LENGTH_SHORT).show()
                loadConfigs()
                
            } catch (e: Exception) {
                Log.e(TAG, "保存配置失败", e)
                Toast.makeText(requireContext(), "保存失败: ${e.message}", Toast.LENGTH_LONG).show()
            }
        }
    }
    
    /**
     * 插入或更新配置
     */
    private suspend fun upsertConfig(key: String, value: String) {
        val existing = repository.getByTypeAndKey(AppConfigKeys.TYPE_FACE_RECOGNITION, key)
        if (existing == null) {
            repository.create(
                Configuration(
                    type = AppConfigKeys.TYPE_FACE_RECOGNITION,
                    key = key,
                    value = value,
                    createTime = Date(),
                    updateTime = Date()
                )
            )
        } else {
            repository.update(
                existing.copy(
                    value = value,
                    updateTime = Date()
                )
            )
        }
    }
    
    /**
     * 激活引擎
     */
    private fun activateEngine() {
        val appId = etAppId.text.toString().trim()
        val sdkKey = etSdkKey.text.toString().trim()
        
        if (appId.isEmpty() || sdkKey.isEmpty()) {
            Toast.makeText(requireContext(), "请先输入APP_ID和SDK_KEY", Toast.LENGTH_SHORT).show()
            return
        }
        
        viewLifecycleOwner.lifecycleScope.launch {
            try {
                val result = withContext(Dispatchers.IO) {
                    // 在线激活
                    FaceEngine.activeOnline(requireContext(), appId, sdkKey)
                }
                
                // ErrorInfo.MOK = 0 表示成功
                // 90114 = MERR_ASF_ALREADY_ACTIVATED 表示已激活
                if (result == ErrorInfo.MOK || result == 90114) {
                    val msg = if (result == 90114) "引擎已激活" else "激活成功"
                    
                    // 保存激活状态到数据库
                    withContext(Dispatchers.IO) {
                        upsertConfig(AppConfigKeys.KEY_FACE_ACTIVATED, "true")
                    }
                    
                    Toast.makeText(requireContext(), msg, Toast.LENGTH_SHORT).show()
                    checkActivationStatus()
                    Log.i(TAG, "引擎激活成功，已保存激活状态到数据库")
                    
                    // 记录激活成功日志
                    requireContext().logConfigChange(
                        scope = viewLifecycleOwner.lifecycleScope,
                        subType = "FACE_ENGINE_ACTIVATE",
                        description = "人脸识别引擎激活成功",
                        oldValue = "未激活",
                        newValue = "已激活 - 错误码: $result"
                    )
                } else {
                    val errorMsg = getErrorMessage(result)
                    Toast.makeText(requireContext(), "激活失败: $errorMsg", Toast.LENGTH_LONG).show()
                    Log.e(TAG, "激活失败，错误码: $result")
                    
                    // 记录激活失败日志
                    requireContext().logConfigChange(
                        scope = viewLifecycleOwner.lifecycleScope,
                        subType = "FACE_ENGINE_ACTIVATE",
                        description = "人脸识别引擎激活失败: $errorMsg",
                        oldValue = "未激活",
                        newValue = "激活失败 - 错误码: $result"
                    )
                }
                
            } catch (e: Exception) {
                Log.e(TAG, "激活引擎异常", e)
                Toast.makeText(requireContext(), "激活异常: ${e.message}", Toast.LENGTH_LONG).show()
            }
        }
    }
    
    /**
     * 检查激活状态
     */
    private fun checkActivationStatus() {
        viewLifecycleOwner.lifecycleScope.launch {
            try {
                // 先检查数据库中是否有APP_ID和SDK_KEY配置
                val (appId, sdkKey) = withContext(Dispatchers.IO) {
                    val appIdConfig = repository.getByTypeAndKey(
                        AppConfigKeys.TYPE_FACE_RECOGNITION,
                        AppConfigKeys.KEY_FACE_APP_ID
                    )
                    val sdkKeyConfig = repository.getByTypeAndKey(
                        AppConfigKeys.TYPE_FACE_RECOGNITION,
                        AppConfigKeys.KEY_FACE_SDK_KEY
                    )
                    Pair(appIdConfig?.value, sdkKeyConfig?.value)
                }
                
                // 如果没有配置APP_ID或SDK_KEY，直接显示未激活
                if (appId.isNullOrEmpty() || sdkKey.isNullOrEmpty()) {
                    tvActivationStatus.text = "未激活"
                    tvActivationStatus.setTextColor(
                        androidx.core.content.ContextCompat.getColor(
                            requireContext(),
                            android.R.color.holo_red_dark
                        )
                    )
                    Log.d(TAG, "未配置APP_ID或SDK_KEY，引擎未激活")
                    return@launch
                }
                
                // 有配置则检查激活状态
                val activeFileInfo = withContext(Dispatchers.IO) {
                    ActiveFileInfo()
                }
                
                val result = withContext(Dispatchers.IO) {
                    FaceEngine.getActiveFileInfo(requireContext(), activeFileInfo)
                }
                
                if (result == ErrorInfo.MOK) {
                    tvActivationStatus.text = "已激活"
                    tvActivationStatus.setTextColor(
                        androidx.core.content.ContextCompat.getColor(
                            requireContext(),
                            android.R.color.holo_green_dark
                        )
                    )
                    
                    // 同步激活状态到数据库
                    withContext(Dispatchers.IO) {
                        val activatedConfig = repository.getByTypeAndKey(
                            AppConfigKeys.TYPE_FACE_RECOGNITION,
                            AppConfigKeys.KEY_FACE_ACTIVATED
                        )
                        // 如果数据库中的状态不是 true，则更新
                        if (activatedConfig?.value != "true") {
                            upsertConfig(AppConfigKeys.KEY_FACE_ACTIVATED, "true")
                            Log.i(TAG, "已同步激活状态到数据库")
                        }
                    }
                    
                    Log.d(TAG, "引擎已激活")
                } else {
                    tvActivationStatus.text = "未激活"
                    tvActivationStatus.setTextColor(
                        androidx.core.content.ContextCompat.getColor(
                            requireContext(),
                            android.R.color.holo_red_dark
                        )
                    )
                    
                    // 同步未激活状态到数据库
                    withContext(Dispatchers.IO) {
                        val activatedConfig = repository.getByTypeAndKey(
                            AppConfigKeys.TYPE_FACE_RECOGNITION,
                            AppConfigKeys.KEY_FACE_ACTIVATED
                        )
                        // 如果数据库中的状态不是 false，则更新
                        if (activatedConfig?.value != "false") {
                            upsertConfig(AppConfigKeys.KEY_FACE_ACTIVATED, "false")
                            Log.i(TAG, "已同步未激活状态到数据库")
                        }
                    }
                    
                    Log.d(TAG, "引擎未激活，错误码: $result")
                }
                
            } catch (e: Exception) {
                Log.e(TAG, "检查激活状态异常", e)
                tvActivationStatus.text = "未激活"
                tvActivationStatus.setTextColor(
                    androidx.core.content.ContextCompat.getColor(
                        requireContext(),
                        android.R.color.holo_red_dark
                    )
                )
            }
        }
    }
    
    /**
     * 获取错误信息
     */
    private fun getErrorMessage(errorCode: Int): String {
        return when (errorCode) {
            ErrorInfo.MOK -> "成功"
            ErrorInfo.MERR_BASIC_BASE -> "基础错误"
            ErrorInfo.MERR_INVALID_PARAM -> "无效参数"
            ErrorInfo.MERR_UNSUPPORTED -> "不支持的操作"
            else -> {
                // 根据错误码范围提供更友好的提示
                when {
                    errorCode in 90100..90199 -> "激活相关错误(错误码: $errorCode)"
                    errorCode in 81900..81999 -> "网络相关错误(错误码: $errorCode)"
                    errorCode in 28600..28699 -> "参数相关错误(错误码: $errorCode)"
                    else -> "未知错误(错误码: $errorCode)"
                }
            }
        }
    }
    
    /**
     * 页面加载时隐藏键盘
     */
    private fun hideKeyboardOnLoad() {
        view?.post {
            etAppId.clearFocus()
            etSdkKey.clearFocus()
            
            val imm = requireContext().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.hideSoftInputFromWindow(view?.windowToken, 0)
            
            view?.requestFocus()
            
            setupEditTextFocusHandling()
        }
    }
    
    /**
     * 设置EditText焦点处理
     */
    private fun setupEditTextFocusHandling() {
        val editTexts = listOf(etAppId, etSdkKey)
        
        editTexts.forEach { editText ->
            editText.setOnClickListener {
                editText.isFocusableInTouchMode = true
                editText.requestFocus()
                
                val imm = requireContext().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT)
            }
            
            editText.setOnFocusChangeListener { _, hasFocus ->
                if (!hasFocus) {
                    editText.isFocusableInTouchMode = false
                }
            }
        }
    }
}